package com.itheima.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.domain.Permission;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }
        //根据用户id查询用户对应的角色
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findById(userId);
        for (Role role : roles) {
            //根据角色id查询对应权限
            Integer roleId = role.getId();
            Set<Permission> permissions = permissionDao.findById(roleId);
            role.setPermissions(permissions);
        }
        user.setRoles(roles);
        return user;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //忽略字符串里的空格
        if (queryString != null && queryString != "") {
            queryString = queryString.replaceAll(" ","");
        }
        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = userDao.findCondition(queryString);
        long total = page.getTotal();
        List<User> result = page.getResult();

        return new PageResult(total,result);
    }

    @Override
    public void add(User user) {
        userDao.add(user);
    }

    @Override
    public void updateRole(Integer id, Integer[] ids) {
        userDao.delete(id);
        if (ids != null && ids.length > 0){
            for (Integer integer : ids) {
                Map<String,Integer> map = new HashMap<>();
                map.put("userId",id);
                map.put("roleId",integer);
                userDao.insertUserAndRole(map);
            }
        }

    }
}
